package com.vehicle.utils;

import com.alibaba.fastjson2.JSONObject;

import java.security.MessageDigest;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class VehicleStringUtil {

    /**
     * 将对象转为JSON字符串时，自动过滤掉Base64内容（如图片、文件流等）
     * 会把Base64字符串替换成 "@base64_xxx_长度_MD5"
     */
    public static String toNonBase64JsonString(Object obj) {
        try {
            if (Objects.isNull(obj)) {
                return null;
            }
            String json = (obj instanceof String) ? (String) obj : JSONObject.toJSONString(obj);

            json = json.replaceAll("\"(?:username|password|company_code)\"\\s*:\\s*\"[^\"]*\"\\s*,?", "");

            // 清理可能留下的多余逗号（如 {"a":1,, "b":2}）
            json = json.replaceAll(",\\s*,", ",");

            // 清理多余逗号在大括号或方括号前
            json = json.replaceAll(",\\s*([}\\]])", "$1");

            // 匹配常见 Base64 前缀：/9j/（jpg）、iVBOR（png）、JVBER（pdf）、UEsD（zip/docx）
            Pattern pattern = Pattern.compile("\"((?:/9j/|iVBOR|JVBER|UEsD)[A-Za-z0-9+/=\\r\\n]+)\"");
            Matcher matcher = pattern.matcher(json);
            StringBuilder sb = new StringBuilder();

            while (matcher.find()) {
                String base64 = matcher.group(1);
                String md5 = calcMD5(base64);
                String replacement = "\"@base64_" + base64.substring(0, 4)
                        + "_" + base64.length()
                        + "_" + md5 + "\"";
                matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
            }
            matcher.appendTail(sb);
            return sb.toString();

        } catch (Throwable e) {
            return "toNonBase64JsonString error: " + e.getMessage();
        }
    }

    /**
     * 计算字符串的MD5摘要
     */
    private static String calcMD5(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(str.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (Exception e) {
            return "md5err";
        }
    }



}
